//
//  LoopStatusCellViewModel.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/11.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
//import YYText

//表情正则表达式对象
let emoticonRegex = try! NSRegularExpression(pattern: "\\[.*?\\]", options: [])
//话题
let topicRegex = try! NSRegularExpression(pattern: "#.*?#", options: [])
//@某人
let atSomeOneRegex = try! NSRegularExpression(pattern: "@\\w+", options: [])
//url
let urlRegex = try! NSRegularExpression(pattern: "[a-zA-z]+://[^\\s]*", options: [])

class LoopStatusCellViewModel: NSObject {

    var iconUrl:URL?
    
    var mbrankImage:UIImage?
    
    var verifitedImage:UIImage?
    //转发的文字
    var reposts_count:String?
    //评论的文字
    var comments_count:String?
    //点赞的文字
    var attitudes_count:String?
    
    var sourceText:String?
    
    var finallyContent:NSAttributedString?
    
    var retweetFinallyContent:NSAttributedString?
    
    var rowHeight:CGFloat = 300
    
    var statusModel:LoopStatus?{
        didSet{
        //处理用户头像地址
            iconUrl = URL(string: statusModel?.user?.avatar_large ?? "")
            reposts_count = dealToolBarText(count: statusModel?.reposts_count ?? 0, defaultText: "转发")
            comments_count = dealToolBarText(count: statusModel?.comments_count ?? 0, defaultText: "评论")
            attitudes_count = dealToolBarText(count: statusModel?.attitudes_count ?? 0, defaultText: "赞")
            
            sourceText = dealSourceText()
            finallyContent = dealTextEmotion(text: statusModel?.text ?? "")
            retweetFinallyContent = dealTextEmotion(text: statusModel?.retweeted_status?.text ?? "")
            
            dealmbrankImage()
            dealverifitedImage()
            
            
        }
    
    }
    
    private func dealTextEmotion(text:String)->NSAttributedString{
        let strM = NSMutableAttributedString(string: text)
        let matchResults = emoticonRegex.matches(in: text, options: [], range: NSMakeRange(0, text.characters.count))
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        for result in matchResults.reversed() {
            let range = result.rangeAt(0)
            let sub = (text as NSString).substring(with: range)
            print(sub)
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub){
                let bundle = HMEmoticonTools.sharedEmoticonTools.emoticonBundle
                
                let image = UIImage(named: em.imagePath!, in: bundle, compatibleWith: nil)
            
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width: lineHeight, height: lineHeight), alignTo: font, alignment: .center)
                
                strM.replaceCharacters(in: range, with: imageText)
                
                
            }
        }
        strM.addAttributes([NSFontAttributeName : font], range: NSRange(location: 0, length: strM.length))
        addHighlightedForText(regx: atSomeOneRegex, strM: strM)
        addHighlightedForText(regx: topicRegex, strM: strM)
        addHighlightedForText(regx: urlRegex, strM: strM)

        return strM
    }
    
    private func addHighlightedForText(regx:NSRegularExpression, strM:NSMutableAttributedString){
        let str = strM.string
        let results = regx.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        for result in results {
            let range = result.rangeAt(0)
            strM.addAttributes([NSForegroundColorAttributeName : UIColor.init(red: 41/255.0, green: 153/255.0, blue: 239/255.0, alpha: 1)], range: range)

            let border = YYTextBorder(fill: UIColor.init(red: 201/255.0, green: 212/255.0, blue: 226/255.0, alpha: 1), cornerRadius: 3)
            let highlighted = YYTextHighlight()
            highlighted.setColor(UIColor.init(red: 41/255.0, green: 153/255.0, blue: 239/255.0, alpha: 1))
            highlighted.setBackgroundBorder(border)
            strM.yy_setTextHighlight(highlighted, range: range)
        }
    
    }
    
    var timeText:String?{
        let dateString = statusModel?.created_at ?? ""
        //Mon Dec 12 19:08:44 +0800 2016
        sharedDateFormatter.dateFormat = "EEE MMM dd HH:mm:ss zzz yyyy"
        //根据微博创建时间字符串,生成一个时间
        let weiboDate = sharedDateFormatter.date(from: dateString)
        
        guard let sinaDate = weiboDate else {
            return ""
        }
        //创建日历对象,用以判断时间
        let calender = Calendar.current
        
        //根据微博日期判断微博是否是当年的
        if isCurrentYear(targetDate: sinaDate) {
            if calender.isDateInToday(sinaDate) {
                let date = Date()
                let detla = date.timeIntervalSince(sinaDate)
                if detla < 60 {
                    return "\(Int(detla))秒之前"
                }else if detla < 3600 {
                    return "\(Int(detla) / 60)分钟之前"
                }else{
                    sharedDateFormatter.dateFormat = "hh:mm"
                    return sharedDateFormatter.string(from: sinaDate)
                }
                
            }else if calender.isDateInYesterday(sinaDate){
                sharedDateFormatter.dateFormat = "昨天 hh:mm"
                return sharedDateFormatter.string(from: sinaDate)
            }else{
                sharedDateFormatter.dateFormat = "mm:dd"
                return sharedDateFormatter.string(from: sinaDate)
                
            }
        }
        sharedDateFormatter.dateFormat = "yyyy-MM-dd"
        return sharedDateFormatter.string(from: sinaDate)
    }
    
    private func isCurrentYear(targetDate:Date)->Bool{
        //拿到当前日期
        let currentDate = Date()
        //设置日期格式
        sharedDateFormatter.dateFormat = "yyyy"
        //将日期转换成所需格式
        let currrentYear = sharedDateFormatter.string(from: currentDate)
        let targetYear = sharedDateFormatter.string(from: targetDate)
        return currrentYear == targetYear
    }
    
    //处理工具栏中显示的方法
    func dealToolBarText(count:Int,defaultText:String)->String{
    
        if count == 0 {
            return defaultText
        }
        if count >= 10000 {
            return "\(Float(count / 1000)/10)万"
        }
        return count.description
    }
    
    
    //处理当前微博来源的方法
    private func dealSourceText()->String{
        let source = statusModel?.source ?? ""
        //<a href="http://app.weibo.com/t/feed/6vtZb0" rel="nofollow">微博 weibo.com</a>
        //<a href="http://app.weibo.com/t/feed/6ghA0p" rel="nofollow">搜狗高速浏览器</a>
        let startString = "\">"
        let stopString = "</a>"
        guard let startRange = source.range(of: startString),let stopRange = source.range(of: stopString) else{
            return "来自未知区域"
        }
        //从范围后面开始
        let startIndex = startRange.upperBound
        //从范围前面开始
        let stopIndex = stopRange.lowerBound
        
        let renturnRange = startIndex..<stopIndex
        
        return "来自 \(source.substring(with: renturnRange))"
    }
    
    //处理图片来源
    var imageArray:[LoopHomePicture]?{
        if statusModel?.retweeted_status != nil{
            
            return statusModel?.retweeted_status?.pic_urls
        }
        return statusModel?.pic_urls
        
    }
    
    //处理VIP等级图片的方法
    private func dealmbrankImage(){
        let mbrank = statusModel?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    
    }
    
    //处理微博认证的方法
    private func dealverifitedImage(){
        /// 认证类型: -1：没有认证，0：认证用户，2,3,5: 企业认证，220: 达人
        let type = statusModel?.user?.verified_type ?? -1
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            verifitedImage = nil
        }
    }
    
    
}
